<template>
  <div class="itineraries">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>我的行程</span>
          <el-button type="primary" @click="showCreateDialog = true">
            <el-icon><Plus /></el-icon>
            创建行程
          </el-button>
        </div>
      </template>

      <el-table
        :data="itineraries"
        v-loading="loading"
        stripe
        style="width: 100%"
        empty-text="暂无行程，点击上方按钮创建您的第一个行程"
      >
        <el-table-column prop="title" label="行程标题" width="200" />
        <el-table-column prop="start_date" label="开始日期" width="120" />
        <el-table-column prop="end_date" label="结束日期" width="120" />
        <el-table-column prop="total_budget" label="预算" width="120">
          <template #default="scope">
            ¥{{ scope.row.total_budget }}
          </template>
        </el-table-column>
        <el-table-column label="天数" width="100">
          <template #default="scope">
            {{ getDaysCount(scope.row.start_date, scope.row.end_date) }} 天
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="viewItinerary(scope.row)"
            >
              查看
            </el-button>
            <el-button
              type="warning"
              size="small"
              @click="editItinerary(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="deleteItinerary(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 创建行程对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      title="创建行程"
      width="600px"
      @close="resetForm"
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="formRef"
        :label-width="isMobile ? 'auto' : '100px'"
        :label-position="isMobile ? 'top' : 'right'"
      >
        <el-form-item label="行程标题" prop="title">
          <el-input v-model="form.title" placeholder="例如：南昌三日游" />
        </el-form-item>
        <el-form-item label="开始日期" prop="start_date">
          <el-date-picker
            v-model="form.start_date"
            type="date"
            placeholder="选择开始日期"
            style="width: 100%"
            :disabled-date="(date) => date < new Date().setHours(0, 0, 0, 0)"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="结束日期" prop="end_date">
          <el-date-picker
            v-model="form.end_date"
            type="date"
            placeholder="选择结束日期"
            style="width: 100%"
            :disabled-date="(date) => {
              if (form.start_date) {
                return date < new Date(form.start_date).setHours(0, 0, 0, 0)
              }
              return date < new Date().setHours(0, 0, 0, 0)
            }"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
          <div class="form-tip" v-if="form.start_date && form.end_date">
            {{ getDaysCount(form.start_date, form.end_date) }} 天行程
          </div>
        </el-form-item>
        <el-form-item label="总预算" prop="total_budget">
          <el-input-number
            v-model="form.total_budget"
            :min="0"
            :max="50000"
            :step="100"
            :precision="0"
            style="width: 100%"
            controls-position="right"
          />
          <div class="form-tip">建议预算范围：500-10000元</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button @click="resetForm">重置</el-button>
        <el-button type="primary" @click="createItinerary" :loading="creating">
          创建
        </el-button>
      </template>
    </el-dialog>

    <!-- 编辑行程对话框 -->
    <el-dialog
      v-model="showEditDialog"
      title="编辑行程"
      width="600px"
      @close="editingItineraryId = null; originalItineraryData = null; resetForm()"
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="editFormRef"
        :label-width="isMobile ? 'auto' : '100px'"
        :label-position="isMobile ? 'top' : 'right'"
      >
        <el-form-item label="行程标题" prop="title">
          <el-input v-model="form.title" placeholder="例如：南昌三日游" />
        </el-form-item>
        <el-form-item label="开始日期" prop="start_date">
          <el-date-picker
            v-model="form.start_date"
            type="date"
            placeholder="选择开始日期"
            style="width: 100%"
            :disabled-date="(date) => date < new Date().setHours(0, 0, 0, 0)"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="结束日期" prop="end_date">
          <el-date-picker
            v-model="form.end_date"
            type="date"
            placeholder="选择结束日期"
            style="width: 100%"
            :disabled-date="(date) => {
              if (form.start_date) {
                return date < new Date(form.start_date).setHours(0, 0, 0, 0)
              }
              return date < new Date().setHours(0, 0, 0, 0)
            }"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
          <div class="form-tip" v-if="form.start_date && form.end_date">
            {{ getDaysCount(form.start_date, form.end_date) }} 天行程
          </div>
        </el-form-item>
        <el-form-item label="总预算" prop="total_budget">
          <el-input-number
            v-model="form.total_budget"
            :min="0"
            :max="50000"
            :step="100"
            :precision="0"
            style="width: 100%"
            controls-position="right"
          />
          <div class="form-tip">建议预算范围：500-10000元</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditDialog = false; editingItineraryId = null; originalItineraryData = null; resetForm()">取消</el-button>
        <el-button @click="resetForm">重置</el-button>
        <el-button type="primary" @click="updateItinerary" :loading="updating">
          保存
        </el-button>
      </template>
    </el-dialog>

    <!-- 行程详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      :title="currentItinerary?.title"
      width="800px"
    >
      <div v-if="currentItinerary">
        <div style="margin-bottom: 20px; text-align: right;">
          <el-dropdown trigger="click" @command="(cmd) => exportItinerary(cmd)">
            <el-button type="primary" :icon="Download">
              导出行程
              <el-icon class="el-icon--right"><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="txt">
                  <el-icon><Document /></el-icon>
                  导出为文本 (.txt)
                </el-dropdown-item>
                <el-dropdown-item command="json">
                  <el-icon><Files /></el-icon>
                  导出为JSON (.json)
                </el-dropdown-item>
                <el-dropdown-item command="pdf">
                  <el-icon><DocumentCopy /></el-icon>
                  导出为PDF (.pdf)
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        
        <el-descriptions :column="2" border>
          <el-descriptions-item label="开始日期">
            {{ currentItinerary.start_date }}
          </el-descriptions-item>
          <el-descriptions-item label="结束日期">
            {{ currentItinerary.end_date }}
          </el-descriptions-item>
          <el-descriptions-item label="总预算">
            ¥{{ currentItinerary.total_budget }}
          </el-descriptions-item>
          <el-descriptions-item label="天数">
            {{ getDaysCount(currentItinerary.start_date, currentItinerary.end_date) }} 天
          </el-descriptions-item>
        </el-descriptions>

        <el-divider />

        <!-- 行程提醒管理 -->
        <div class="reminders-section">
          <div class="section-header">
            <h3>行程提醒</h3>
            <el-button type="primary" size="small" @click="showReminderDialog = true">
              <el-icon><Bell /></el-icon>
              添加提醒
            </el-button>
          </div>
          <div v-if="reminders && reminders.length > 0" class="reminders-list">
            <el-card v-for="reminder in reminders" :key="reminder.id" class="reminder-card">
              <div class="reminder-content">
                <div class="reminder-info">
                  <el-tag :type="getReminderTypeTag(reminder.reminder_type)" size="small">
                    {{ getReminderTypeName(reminder.reminder_type) }}
                  </el-tag>
                  <span class="reminder-time">{{ formatReminderTime(reminder.reminder_time) }}</span>
                  <el-tag :type="getStatusTag(reminder.status)" size="small">
                    {{ getStatusName(reminder.status) }}
                  </el-tag>
                </div>
                <p class="reminder-message">{{ reminder.message }}</p>
              </div>
              <div class="reminder-actions">
                <el-switch
                  v-model="reminder.is_enabled"
                  @change="toggleReminder(reminder.id, reminder.is_enabled)"
                  :loading="togglingReminder === reminder.id"
                />
                <el-button
                  type="danger"
                  size="small"
                  text
                  @click="deleteReminder(reminder.id)"
                  :loading="deletingReminder === reminder.id"
                >
                  删除
                </el-button>
              </div>
            </el-card>
          </div>
          <el-empty v-else description="暂无提醒，点击上方按钮添加提醒" :image-size="80" />
        </div>

        <el-divider />

        <div v-if="currentItinerary.days && currentItinerary.days.length > 0">
          <h3>每日计划</h3>
          <el-timeline>
            <el-timeline-item
              v-for="day in currentItinerary.days"
              :key="day.id"
              :timestamp="`第${day.day_number}天 - ${day.date}`"
              placement="top"
            >
              <el-card>
                <div v-if="day.activities && day.activities.length > 0">
                  <div
                    v-for="activity in day.activities"
                    :key="activity.id"
                    class="activity-item"
                  >
                    <div class="activity-header">
                      <h4>{{ activity.attraction_name || activity.attraction?.name }}</h4>
                      <div class="activity-actions">
                        <el-button
                          type="primary"
                          size="small"
                          text
                          @click="editActivity(activity, day.id)"
                        >
                          编辑
                        </el-button>
                        <el-button
                          type="danger"
                          size="small"
                          text
                          @click="deleteActivity(activity.id)"
                          :loading="deletingActivityId === activity.id"
                        >
                          删除
                        </el-button>
                      </div>
                    </div>
                    <p>时间：{{ activity.start_time }} - {{ activity.end_time }}</p>
                    <p>交通方式：{{ getTransportModeName(activity.transport_mode) }}</p>
                    <p v-if="activity.notes">备注：{{ activity.notes }}</p>
                  </div>
                </div>
                <div v-else class="empty-activities">
                  <el-empty description="暂无活动安排" :image-size="80" />
                </div>
                <el-button
                  type="primary"
                  size="small"
                  @click="showAddActivityDialog(day.id)"
                  style="margin-top: 10px; width: 100%"
                >
                  <el-icon><Plus /></el-icon>
                  添加活动
                </el-button>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </div>
        <el-empty v-else description="暂无每日计划" />
      </div>
    </el-dialog>

    <!-- 添加提醒对话框 -->
    <el-dialog
      v-model="showReminderDialog"
      title="添加行程提醒"
      width="600px"
    >
      <el-form
        :model="reminderForm"
        :rules="reminderRules"
        ref="reminderFormRef"
        :label-width="isMobile ? 'auto' : '100px'"
        :label-position="isMobile ? 'top' : 'right'"
      >
        <el-form-item label="提醒类型" prop="reminder_type">
          <el-select v-model="reminderForm.reminder_type" placeholder="选择提醒类型" style="width: 100%">
            <el-option label="行程开始提醒" value="start" />
            <el-option label="每日提醒" value="day" />
            <el-option label="活动提醒" value="activity" />
          </el-select>
        </el-form-item>
        <el-form-item label="提醒时间" prop="reminder_time">
          <el-date-picker
            v-model="reminderForm.reminder_time"
            type="datetime"
            placeholder="选择提醒时间"
            style="width: 100%"
            :disabled-date="(date) => date < new Date()"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DDTHH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="提醒内容" prop="message">
          <el-input
            v-model="reminderForm.message"
            type="textarea"
            :rows="3"
            placeholder="输入提醒内容（可选，留空将使用默认消息）"
          />
        </el-form-item>
        <el-form-item label="启用状态">
          <el-switch v-model="reminderForm.is_enabled" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showReminderDialog = false">取消</el-button>
        <el-button type="primary" @click="createReminder" :loading="creatingReminder">
          创建
        </el-button>
      </template>
    </el-dialog>

    <!-- 添加/编辑活动对话框 -->
    <el-dialog
      v-model="showActivityDialog"
      :title="editingActivityId ? '编辑活动' : '添加活动'"
      width="600px"
      @close="resetActivityForm()"
    >
      <el-form
        :model="activityForm"
        :rules="activityRules"
        ref="activityFormRef"
        :label-width="isMobile ? 'auto' : '100px'"
        :label-position="isMobile ? 'top' : 'right'"
      >
        <el-form-item label="景点" prop="attraction_id">
          <el-select
            v-model="activityForm.attraction_id"
            placeholder="选择景点"
            filterable
            style="width: 100%"
            :loading="loadingAttractions"
          >
            <el-option
              v-for="attraction in attractions"
              :key="attraction.id"
              :label="attraction.name"
              :value="attraction.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="start_time">
          <el-time-picker
            v-model="activityForm.start_time"
            placeholder="选择开始时间"
            format="HH:mm"
            value-format="HH:mm"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="end_time">
          <el-time-picker
            v-model="activityForm.end_time"
            placeholder="选择结束时间"
            format="HH:mm"
            value-format="HH:mm"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="交通方式" prop="transport_mode">
          <el-select v-model="activityForm.transport_mode" placeholder="选择交通方式" style="width: 100%">
            <el-option label="步行" value="walking" />
            <el-option label="自驾" value="driving" />
            <el-option label="公共交通" value="transit" />
            <el-option label="出租车" value="taxi" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="activityForm.notes"
            type="textarea"
            :rows="3"
            placeholder="输入备注信息（可选）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showActivityDialog = false; resetActivityForm()">取消</el-button>
        <el-button type="primary" @click="saveActivity" :loading="creatingActivity">
          {{ editingActivityId ? '保存' : '添加' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, watch, onUnmounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Bell, Download, Document, Files, ArrowDown, DocumentCopy } from '@element-plus/icons-vue'
import TravelAPI from '../api/travel'
import notificationManager from '../utils/notification'

export default {
  name: 'Itineraries',
  components: {
    Plus,
    Bell
  },
  setup() {
    // 检测移动端
    const isMobile = computed(() => {
      return window.innerWidth < 768
    })
    
    const loading = ref(false)
    const creating = ref(false)
    const updating = ref(false)
    const itineraries = ref([])
    const showCreateDialog = ref(false)
    const showEditDialog = ref(false)
    const showDetailDialog = ref(false)
    const showReminderDialog = ref(false)
    const showActivityDialog = ref(false)
    const currentItinerary = ref(null)
    const editingItineraryId = ref(null)
    const originalItineraryData = ref(null) // 保存原始行程数据，用于重置
    const formRef = ref(null)
    const editFormRef = ref(null) // 编辑对话框的表单引用
    const reminderFormRef = ref(null)
    const reminders = ref([])
    const creatingReminder = ref(false)
    const togglingReminder = ref(null)
    const deletingReminder = ref(null)

    const form = reactive({
      title: '',
      start_date: null,
      end_date: null,
      total_budget: 1000
    })

    const activityForm = reactive({
      attraction_id: null,
      start_time: null,
      end_time: null,
      transport_mode: 'walking',
      notes: '',
      day_id: null
    })

    const activityFormRef = ref(null)
    const creatingActivity = ref(false)
    const editingActivityId = ref(null)
    const deletingActivityId = ref(null)
    const attractions = ref([])
    const loadingAttractions = ref(false)

    const reminderForm = reactive({
      reminder_type: 'day',
      reminder_time: null,
      message: '',
      is_enabled: true
    })

    const activityRules = {
      attraction_id: [
        { required: true, message: '请选择景点', trigger: 'change' }
      ],
      start_time: [
        { required: true, message: '请选择开始时间', trigger: 'change' }
      ],
      end_time: [
        { required: true, message: '请选择结束时间', trigger: 'change' }
      ],
      transport_mode: [
        { required: true, message: '请选择交通方式', trigger: 'change' }
      ]
    }

    const reminderRules = {
      reminder_type: [
        { required: true, message: '请选择提醒类型', trigger: 'change' }
      ],
      reminder_time: [
        { required: true, message: '请选择提醒时间', trigger: 'change' }
      ]
    }

    const rules = {
      title: [
        { required: true, message: '请输入行程标题', trigger: 'blur' },
        { min: 2, max: 50, message: '标题长度在 2 到 50 个字符', trigger: 'blur' }
      ],
      start_date: [
        { required: true, message: '请选择开始日期', trigger: 'change' },
        {
          validator: (rule, value, callback) => {
            if (!value) {
              callback()
              return
            }
            const today = new Date()
            today.setHours(0, 0, 0, 0)
            const selectedDate = new Date(value)
            selectedDate.setHours(0, 0, 0, 0)
            if (selectedDate < today) {
              callback(new Error('开始日期不能早于今天'))
            } else {
              callback()
            }
          },
          trigger: 'change'
        }
      ],
      end_date: [
        { required: true, message: '请选择结束日期', trigger: 'change' },
        {
          validator: (rule, value, callback) => {
            if (!value) {
              callback()
              return
            }
            if (form.start_date) {
              const startDate = new Date(form.start_date)
              startDate.setHours(0, 0, 0, 0)
              const endDate = new Date(value)
              endDate.setHours(0, 0, 0, 0)
              if (endDate < startDate) {
                callback(new Error('结束日期不能早于开始日期'))
              } else {
                // 检查行程天数是否过长（例如超过30天）
                const daysDiff = Math.ceil((endDate - startDate) / (1000 * 60 * 60 * 24))
                if (daysDiff > 30) {
                  callback(new Error('行程天数不能超过30天'))
                } else {
                  callback()
                }
              }
            } else {
              callback()
            }
          },
          trigger: 'change'
        }
      ],
      total_budget: [
        { required: true, message: '请输入预算', trigger: 'blur' },
        { type: 'number', min: 0, message: '预算必须大于等于0', trigger: 'blur' },
        { type: 'number', max: 50000, message: '预算不能超过50000元', trigger: 'blur' }
      ]
    }

    const fetchItineraries = async () => {
      loading.value = true
      try {
        const response = await TravelAPI.getItineraries()
        itineraries.value = response.results || response || []
      } catch (error) {
        import('../utils/errorHandler').then(({ handleApiError }) => {
          handleApiError(error, { defaultMessage: '获取行程列表失败' })
        })
      } finally {
        loading.value = false
      }
    }

    const createItinerary = async () => {
      if (!formRef.value) return

      try {
        await formRef.value.validate()
        
        // 额外验证：检查日期逻辑
        if (form.start_date && form.end_date) {
          const startDate = new Date(form.start_date)
          const endDate = new Date(form.end_date)
          if (endDate < startDate) {
            ElMessage.warning('结束日期不能早于开始日期')
            return
          }
          
          // 检查行程天数
          const daysDiff = Math.ceil((endDate - startDate) / (1000 * 60 * 60 * 24))
          if (daysDiff > 30) {
            ElMessage.warning('行程天数不能超过30天')
            return
          }
        }
        
        // 验证预算范围
        if (form.total_budget < 0) {
          ElMessage.warning('预算必须大于等于0')
          return
        }
        if (form.total_budget > 50000) {
          ElMessage.warning('预算不能超过50000元')
          return
        }
        
        creating.value = true

        const itineraryData = {
          title: form.title.trim(),
          start_date: form.start_date,
          end_date: form.end_date,
          total_budget: form.total_budget
        }

        await TravelAPI.createItinerary(itineraryData)
        ElMessage.success('行程创建成功')
        showCreateDialog.value = false
        resetForm()
        fetchItineraries()
      } catch (error) {
        import('../utils/errorHandler').then(({ handleApiError }) => {
          handleApiError(error, { defaultMessage: '创建行程失败' })
        })
        let errorMessage = '创建失败'
        if (error.response) {
          const status = error.response.status
          if (status === 400) {
            errorMessage = error.response.data?.error || error.response.data?.detail || '请求参数错误，请检查输入信息'
          } else if (status === 401) {
            errorMessage = '登录已过期，请重新登录'
          } else if (status === 403) {
            errorMessage = '没有权限创建行程'
          } else if (error.response.data?.error) {
            errorMessage = error.response.data.error
          } else if (error.response.data?.detail) {
            errorMessage = error.response.data.detail
          }
        } else if (error.message) {
          if (error.message.includes('timeout') || error.message.includes('Network Error')) {
            errorMessage = '网络错误，请检查网络连接'
          }
        }
        ElMessage.error(errorMessage)
      } finally {
        creating.value = false
      }
    }

    const viewItinerary = async (itinerary) => {
      currentItinerary.value = itinerary
      showDetailDialog.value = true
      // 加载提醒列表
      await fetchReminders(itinerary.id)
    }

    const editItinerary = (itinerary) => {
      editingItineraryId.value = itinerary.id
      // 保存原始数据，用于重置
      originalItineraryData.value = {
        title: itinerary.title,
        start_date: itinerary.start_date,
        end_date: itinerary.end_date,
        total_budget: itinerary.total_budget
      }
      form.title = itinerary.title
      form.start_date = itinerary.start_date
      form.end_date = itinerary.end_date
      form.total_budget = itinerary.total_budget
      showEditDialog.value = true
    }

    const updateItinerary = async () => {
      if (!editFormRef.value || !editingItineraryId.value) return

      try {
        await editFormRef.value.validate()
        
        // 额外验证：检查日期逻辑
        if (form.start_date && form.end_date) {
          const startDate = new Date(form.start_date)
          const endDate = new Date(form.end_date)
          if (endDate < startDate) {
            ElMessage.warning('结束日期不能早于开始日期')
            return
          }
          
          // 检查行程天数
          const daysDiff = Math.ceil((endDate - startDate) / (1000 * 60 * 60 * 24))
          if (daysDiff > 30) {
            ElMessage.warning('行程天数不能超过30天')
            return
          }
        }
        
        // 验证预算范围
        if (form.total_budget < 0) {
          ElMessage.warning('预算必须大于等于0')
          return
        }
        if (form.total_budget > 50000) {
          ElMessage.warning('预算不能超过50000元')
          return
        }
        
        updating.value = true

        const itineraryData = {
          title: form.title.trim(),
          start_date: form.start_date,
          end_date: form.end_date,
          total_budget: form.total_budget
        }

        await TravelAPI.updateItinerary(editingItineraryId.value, itineraryData)
        ElMessage.success('行程更新成功')
        showEditDialog.value = false
        editingItineraryId.value = null
        originalItineraryData.value = null
        resetForm()
        fetchItineraries()
      } catch (error) {
        import('../utils/errorHandler').then(({ handleApiError }) => {
          handleApiError(error, { defaultMessage: '更新行程失败' })
        })
        let errorMessage = '更新失败'
        if (error.response) {
          const status = error.response.status
          if (status === 400) {
            errorMessage = error.response.data?.error || error.response.data?.detail || '请求参数错误，请检查输入信息'
          } else if (status === 401) {
            errorMessage = '登录已过期，请重新登录'
          } else if (status === 403) {
            errorMessage = '没有权限更新行程'
          } else if (status === 404) {
            errorMessage = '行程不存在'
          } else if (error.response.data?.error) {
            errorMessage = error.response.data.error
          } else if (error.response.data?.detail) {
            errorMessage = error.response.data.detail
          }
        } else if (error.message) {
          if (error.message.includes('timeout') || error.message.includes('Network Error')) {
            errorMessage = '网络错误，请检查网络连接'
          }
        }
        ElMessage.error(errorMessage)
      } finally {
        updating.value = false
      }
    }

    const fetchReminders = async (itineraryId) => {
      try {
        const response = await TravelAPI.getItineraryReminders(itineraryId)
        reminders.value = response.results || response || []
      } catch (error) {
        import('../utils/logger').then(({ logger }) => {
          logger.error('获取提醒列表失败:', error)
        })
        reminders.value = []
      }
    }

    const createReminder = async () => {
      if (!reminderFormRef.value || !currentItinerary.value) return

      try {
        await reminderFormRef.value.validate()

        if (!reminderForm.reminder_time) {
          ElMessage.warning('请选择提醒时间')
          return
        }

        // 转换时间格式为ISO格式
        const reminderTime = new Date(reminderForm.reminder_time).toISOString()

        creatingReminder.value = true

        const reminderData = {
          reminder_type: reminderForm.reminder_type,
          reminder_time: reminderTime,
          message: reminderForm.message.trim() || undefined,
          is_enabled: reminderForm.is_enabled
        }

        await TravelAPI.createItineraryReminder(currentItinerary.value.id, reminderData)
        ElMessage.success('提醒创建成功')
        showReminderDialog.value = false
        resetReminderForm()
        await fetchReminders(currentItinerary.value.id)
      } catch (error) {
        import('../utils/errorHandler').then(({ handleApiError }) => {
          handleApiError(error, { defaultMessage: '创建提醒失败' })
        })
        let errorMessage = '创建失败'
        if (error.response) {
          const status = error.response.status
          if (status === 400) {
            errorMessage = error.response.data?.error || '请求参数错误'
          } else if (error.response.data?.error) {
            errorMessage = error.response.data.error
          }
        }
        ElMessage.error(errorMessage)
      } finally {
        creatingReminder.value = false
      }
    }

    const toggleReminder = async (reminderId, isEnabled) => {
      try {
        togglingReminder.value = reminderId
        await TravelAPI.toggleReminder(reminderId)
        ElMessage.success(isEnabled ? '提醒已启用' : '提醒已禁用')
        if (currentItinerary.value) {
          await fetchReminders(currentItinerary.value.id)
        }
      } catch (error) {
        import('../utils/errorHandler').then(({ handleApiError }) => {
          handleApiError(error, { defaultMessage: '切换提醒状态失败' })
        })
        ElMessage.error('操作失败')
        // 恢复状态
        const reminder = reminders.value.find(r => r.id === reminderId)
        if (reminder) {
          reminder.is_enabled = !isEnabled
        }
      } finally {
        togglingReminder.value = null
      }
    }

    const deleteReminder = async (reminderId) => {
      try {
        await ElMessageBox.confirm('确定要删除这个提醒吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        deletingReminder.value = reminderId
        await TravelAPI.deleteReminder(reminderId)
        ElMessage.success('删除成功')
        if (currentItinerary.value) {
          await fetchReminders(currentItinerary.value.id)
        }
      } catch (error) {
        if (error !== 'cancel') {
          import('../utils/errorHandler').then(({ handleApiError }) => {
            handleApiError(error, { defaultMessage: '删除提醒失败' })
          })
          ElMessage.error('删除失败')
        }
      } finally {
        deletingReminder.value = null
      }
    }

    const resetReminderForm = () => {
      reminderForm.reminder_type = 'day'
      reminderForm.reminder_time = null
      reminderForm.message = ''
      reminderForm.is_enabled = true
      if (reminderFormRef.value) {
        reminderFormRef.value.clearValidate()
      }
    }

    const getReminderTypeName = (type) => {
      const names = {
        start: '行程开始',
        day: '每日提醒',
        activity: '活动提醒'
      }
      return names[type] || type
    }

    const getReminderTypeTag = (type) => {
      const tags = {
        start: 'success',
        day: 'primary',
        activity: 'warning'
      }
      return tags[type] || ''
    }

    const getStatusName = (status) => {
      const names = {
        pending: '待发送',
        sent: '已发送',
        cancelled: '已取消'
      }
      return names[status] || status
    }

    const getStatusTag = (status) => {
      const tags = {
        pending: 'info',
        sent: 'success',
        cancelled: 'danger'
      }
      return tags[status] || ''
    }

    const formatReminderTime = (timeStr) => {
      if (!timeStr) return ''
      const date = new Date(timeStr)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }

    const deleteItinerary = async (itineraryId) => {
      try {
        await ElMessageBox.confirm('确定要删除这个行程吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await TravelAPI.deleteItinerary(itineraryId)
        ElMessage.success('删除成功')
        fetchItineraries()
      } catch (error) {
        if (error !== 'cancel') {
          import('../utils/errorHandler').then(({ handleApiError }) => {
            handleApiError(error, { defaultMessage: '删除行程失败' })
          })
          let errorMessage = '删除失败'
          if (error.response) {
            const status = error.response.status
            if (status === 401) {
              errorMessage = '登录已过期，请重新登录'
            } else if (status === 403) {
              errorMessage = '没有权限删除此行程'
            } else if (status === 404) {
              errorMessage = '行程不存在'
            } else if (error.response.data?.error) {
              errorMessage = error.response.data.error
            } else if (error.response.data?.detail) {
              errorMessage = error.response.data.detail
            }
          } else if (error.message) {
            errorMessage = error.message
          }
          ElMessage.error(errorMessage)
        }
      }
    }

    const resetForm = () => {
      // 如果在编辑模式下，重置为原始数据；否则重置为空
      if (editingItineraryId.value && originalItineraryData.value) {
        form.title = originalItineraryData.value.title
        form.start_date = originalItineraryData.value.start_date
        form.end_date = originalItineraryData.value.end_date
        form.total_budget = originalItineraryData.value.total_budget
        // 清除编辑对话框的表单验证状态
        if (editFormRef.value) {
          editFormRef.value.clearValidate()
        }
      } else {
        // 创建模式：重置为空
        form.title = ''
        form.start_date = null
        form.end_date = null
        form.total_budget = 1000
        // 清除创建对话框的表单验证状态
        if (formRef.value) {
          formRef.value.clearValidate()
        }
      }
    }
    
    // 监听对话框关闭，重置表单
    watch(showCreateDialog, (visible) => {
      if (!visible) {
        resetForm()
      }
    })

    const getDaysCount = (startDate, endDate) => {
      if (!startDate || !endDate) return 0
      const start = new Date(startDate)
      const end = new Date(endDate)
      const diffTime = Math.abs(end - start)
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
      return diffDays + 1
    }

    const getTransportModeName = (mode) => {
      const names = {
        walking: '步行',
        driving: '自驾',
        transit: '公共交通',
        taxi: '出租车'
      }
      return names[mode] || mode
    }

    const fetchAttractions = async () => {
      if (attractions.value.length > 0) return // 已加载过
      loadingAttractions.value = true
      try {
        const response = await TravelAPI.getAttractions({ page_size: 1000 })
        attractions.value = response.results || response || []
      } catch (error) {
        import('../utils/logger').then(({ logger }) => {
          logger.error('获取景点列表失败:', error)
        })
        attractions.value = []
      } finally {
        loadingAttractions.value = false
      }
    }

    const showAddActivityDialog = async (dayId) => {
      if (!currentItinerary.value) return
      activityForm.day_id = dayId
      editingActivityId.value = null
      resetActivityForm()
      await fetchAttractions()
      showActivityDialog.value = true
    }

    const editActivity = async (activity, dayId) => {
      activityForm.day_id = dayId
      activityForm.attraction_id = activity.attraction || activity.attraction_id
      activityForm.start_time = activity.start_time
      activityForm.end_time = activity.end_time
      activityForm.transport_mode = activity.transport_mode
      activityForm.notes = activity.notes || ''
      editingActivityId.value = activity.id
      await fetchAttractions()
      showActivityDialog.value = true
    }

    const saveActivity = async () => {
      if (!activityFormRef.value || !currentItinerary.value || !activityForm.day_id) return

      try {
        await activityFormRef.value.validate()

        // 验证时间逻辑
        if (activityForm.start_time && activityForm.end_time) {
          const [startHour, startMin] = activityForm.start_time.split(':').map(Number)
          const [endHour, endMin] = activityForm.end_time.split(':').map(Number)
          const startMinutes = startHour * 60 + startMin
          const endMinutes = endHour * 60 + endMin
          
          if (endMinutes <= startMinutes) {
            ElMessage.warning('结束时间必须晚于开始时间')
            return
          }
        }

        creatingActivity.value = true

        const activityData = {
          attraction: activityForm.attraction_id,
          start_time: activityForm.start_time,
          end_time: activityForm.end_time,
          transport_mode: activityForm.transport_mode,
          notes: activityForm.notes.trim() || ''
        }

        if (editingActivityId.value) {
          // 更新活动
          await TravelAPI.updateActivity(
            currentItinerary.value.id,
            activityForm.day_id,
            editingActivityId.value,
            activityData
          )
          ElMessage.success('活动更新成功')
          showActivityDialog.value = false
          resetActivityForm()
          // 重新加载行程详情
          const updatedItinerary = await TravelAPI.getItinerary(currentItinerary.value.id)
          currentItinerary.value = updatedItinerary
        } else {
          // 添加活动
          await TravelAPI.addActivity(
            currentItinerary.value.id,
            activityForm.day_id,
            activityData
          )
          ElMessage.success('活动添加成功')
          showActivityDialog.value = false
          resetActivityForm()
          // 重新加载行程详情
          const updatedItinerary = await TravelAPI.getItinerary(currentItinerary.value.id)
          currentItinerary.value = updatedItinerary
        }
      } catch (error) {
        import('../utils/errorHandler').then(({ handleApiError }) => {
          handleApiError(error, { defaultMessage: editingActivityId.value ? '更新活动失败' : '添加活动失败' })
        })
        let errorMessage = editingActivityId.value ? '更新失败' : '添加失败'
        if (error.response) {
          const status = error.response.status
          if (status === 400) {
            errorMessage = error.response.data?.error || error.response.data?.detail || '请求参数错误'
          } else if (status === 401) {
            errorMessage = '登录已过期，请重新登录'
          } else if (status === 403) {
            errorMessage = '没有权限操作此活动'
          } else if (status === 404) {
            errorMessage = '每日计划不存在'
          } else if (error.response.data?.error) {
            errorMessage = error.response.data.error
          }
        }
        ElMessage.error(errorMessage)
      } finally {
        creatingActivity.value = false
      }
    }

    const deleteActivity = async (activityId) => {
      if (!currentItinerary.value) return
      
      try {
        await ElMessageBox.confirm('确定要删除这个活动吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        deletingActivityId.value = activityId
        
        // 找到活动所属的day_id
        let dayId = null
        for (const day of currentItinerary.value.days || []) {
          const activity = (day.activities || []).find(a => a.id === activityId)
          if (activity) {
            dayId = day.id
            break
          }
        }
        
        if (!dayId) {
          ElMessage.error('无法找到活动所属的每日计划')
          return
        }
        
        await TravelAPI.deleteActivity(
          currentItinerary.value.id,
          dayId,
          activityId
        )
        ElMessage.success('删除成功')
        // 重新加载行程详情
        const updatedItinerary = await TravelAPI.getItinerary(currentItinerary.value.id)
        currentItinerary.value = updatedItinerary
      } catch (error) {
        if (error !== 'cancel') {
          import('../utils/errorHandler').then(({ handleApiError }) => {
            handleApiError(error, { defaultMessage: '删除活动失败' })
          })
          let errorMessage = '删除失败'
          if (error.response) {
            const status = error.response.status
            if (status === 400) {
              errorMessage = error.response.data?.error || '请求参数错误'
            } else if (status === 401) {
              errorMessage = '登录已过期，请重新登录'
            } else if (status === 403) {
              errorMessage = '没有权限删除此活动'
            } else if (status === 404) {
              errorMessage = '活动不存在'
            } else if (error.response.data?.error) {
              errorMessage = error.response.data.error
            }
          }
          ElMessage.error(errorMessage)
        }
      } finally {
        deletingActivityId.value = null
      }
    }

    const resetActivityForm = () => {
      activityForm.attraction_id = null
      activityForm.start_time = null
      activityForm.end_time = null
      activityForm.transport_mode = 'walking'
      activityForm.notes = ''
      activityForm.day_id = null
      editingActivityId.value = null
      if (activityFormRef.value) {
        activityFormRef.value.clearValidate()
      }
    }

    // 检查并获取即将到来的提醒
    const checkUpcomingReminders = async () => {
      try {
        const response = await TravelAPI.getUpcomingReminders()
        const upcomingReminders = response.results || response || []
        
        // 显示通知
        for (const reminder of upcomingReminders) {
          // 检查是否已经显示过这个提醒
          const reminderKey = `reminder_shown_${reminder.id}`
          if (!localStorage.getItem(reminderKey)) {
            await notificationManager.showReminderNotification(reminder)
            // 标记为已显示（5分钟内不再显示）
            localStorage.setItem(reminderKey, 'true')
            setTimeout(() => {
              localStorage.removeItem(reminderKey)
            }, 5 * 60 * 1000) // 5分钟
          }
        }
      } catch (error) {
        // 静默失败，不影响用户体验，但记录日志
        import('../utils/logger').then(({ logger }) => {
          logger.error('检查即将到来的提醒失败:', error)
        })
      }
    }

    // 请求通知权限
    const requestNotificationPermission = async () => {
      try {
        const granted = await notificationManager.requestPermission()
        if (granted) {
          ElMessage.success('通知权限已授予')
        } else {
          ElMessage.warning('通知权限被拒绝，将无法收到提醒通知')
        }
      } catch (error) {
        import('../utils/logger').then(({ logger }) => {
          logger.error('请求通知权限失败:', error)
        })
      }
    }

    /**
     * 导出行程
     */
    const exportItinerary = (format) => {
      if (!currentItinerary.value) {
        ElMessage.warning('请先选择要导出的行程')
        return
      }

      const itinerary = currentItinerary.value
      const days = itinerary.days || []
      const daysCount = getDaysCount(itinerary.start_date, itinerary.end_date)

      if (format === 'txt') {
        // 导出为文本格式
        let content = `行程：${itinerary.title}\n`
        content += `开始日期：${itinerary.start_date}\n`
        content += `结束日期：${itinerary.end_date}\n`
        content += `总预算：¥${itinerary.total_budget}\n`
        content += `天数：${daysCount} 天\n`
        content += `\n${'='.repeat(50)}\n\n`

        if (days.length > 0) {
          days.forEach((day) => {
            content += `第${day.day_number}天 - ${day.date}\n`
            content += `${'-'.repeat(30)}\n`
            
            if (day.activities && day.activities.length > 0) {
              day.activities.forEach((activity, actIndex) => {
                content += `${actIndex + 1}. ${activity.attraction_name || activity.attraction?.name || '未知景点'}\n`
                content += `   时间：${activity.start_time} - ${activity.end_time}\n`
                content += `   交通方式：${getTransportModeName(activity.transport_mode)}\n`
                if (activity.notes) {
                  content += `   备注：${activity.notes}\n`
                }
                content += '\n'
              })
            } else {
              content += '   暂无活动安排\n\n'
            }
          })
        } else {
          content += '暂无每日计划\n'
        }

        // 添加提醒信息
        if (reminders.value && reminders.value.length > 0) {
          content += `\n${'='.repeat(50)}\n`
          content += `行程提醒\n`
          content += `${'-'.repeat(30)}\n`
          reminders.value.forEach((reminder, index) => {
            content += `${index + 1}. ${getReminderTypeName(reminder.reminder_type)} - ${formatReminderTime(reminder.reminder_time)}\n`
            content += `   消息：${reminder.message}\n`
            content += `   状态：${getStatusName(reminder.status)}\n`
            content += `   启用：${reminder.is_enabled ? '是' : '否'}\n\n`
          })
        }

        // 下载文件
        const blob = new Blob([content], { type: 'text/plain;charset=utf-8' })
        const url = URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `${itinerary.title}_${itinerary.start_date}.txt`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        URL.revokeObjectURL(url)
        
        ElMessage.success('行程已导出为文本文件')
      } else if (format === 'json') {
        // 导出为JSON格式
        const exportData = {
          title: itinerary.title,
          start_date: itinerary.start_date,
          end_date: itinerary.end_date,
          total_budget: itinerary.total_budget,
          days_count: daysCount,
          days: days.map(day => ({
            day_number: day.day_number,
            date: day.date,
            activities: (day.activities || []).map(activity => ({
              attraction_name: activity.attraction_name || activity.attraction?.name,
              start_time: activity.start_time,
              end_time: activity.end_time,
              transport_mode: activity.transport_mode,
              notes: activity.notes
            }))
          })),
          reminders: reminders.value.map(reminder => ({
            reminder_type: reminder.reminder_type,
            reminder_time: reminder.reminder_time,
            message: reminder.message,
            status: reminder.status,
            is_enabled: reminder.is_enabled
          })),
          export_time: new Date().toISOString()
        }

        const jsonContent = JSON.stringify(exportData, null, 2)
        const blob = new Blob([jsonContent], { type: 'application/json;charset=utf-8' })
        const url = URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `${itinerary.title}_${itinerary.start_date}.json`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        URL.revokeObjectURL(url)
        
        ElMessage.success('行程已导出为JSON文件')
      } else if (format === 'pdf') {
        // 导出为PDF格式（使用浏览器打印功能）
        try {
          // 创建PDF内容HTML
          let htmlContent = `
            <!DOCTYPE html>
            <html>
            <head>
              <meta charset="UTF-8">
              <title>${itinerary.title}</title>
              <style>
                body {
                  font-family: 'Microsoft YaHei', Arial, sans-serif;
                  padding: 40px;
                  color: #333;
                }
                .header {
                  text-align: center;
                  margin-bottom: 30px;
                  border-bottom: 3px solid #C8102E;
                  padding-bottom: 20px;
                }
                .header h1 {
                  color: #C8102E;
                  margin: 0;
                  font-size: 28px;
                }
                .info-section {
                  margin-bottom: 30px;
                  background: #f5f7fa;
                  padding: 20px;
                  border-radius: 8px;
                }
                .info-row {
                  display: flex;
                  margin-bottom: 10px;
                }
                .info-label {
                  font-weight: bold;
                  width: 120px;
                  color: #606266;
                }
                .day-section {
                  margin-bottom: 30px;
                  page-break-inside: avoid;
                }
                .day-header {
                  background: linear-gradient(135deg, #C8102E 0%, #D4AF37 100%);
                  color: white;
                  padding: 15px;
                  border-radius: 8px 8px 0 0;
                  font-size: 18px;
                  font-weight: bold;
                }
                .day-content {
                  border: 1px solid #ebeef5;
                  border-top: none;
                  padding: 20px;
                  border-radius: 0 0 8px 8px;
                }
                .activity-item {
                  margin-bottom: 15px;
                  padding-bottom: 15px;
                  border-bottom: 1px dashed #ebeef5;
                }
                .activity-item:last-child {
                  border-bottom: none;
                }
                .activity-title {
                  font-size: 16px;
                  font-weight: bold;
                  color: #C8102E;
                  margin-bottom: 8px;
                }
                .activity-detail {
                  color: #606266;
                  margin: 5px 0;
                  font-size: 14px;
                }
                .reminders-section {
                  margin-top: 30px;
                  padding-top: 20px;
                  border-top: 2px solid #ebeef5;
                }
                .reminder-item {
                  margin-bottom: 15px;
                  padding: 15px;
                  background: #f5f7fa;
                  border-radius: 8px;
                  border-left: 4px solid #D4AF37;
                }
                .footer {
                  margin-top: 40px;
                  text-align: center;
                  color: #909399;
                  font-size: 12px;
                  border-top: 1px solid #ebeef5;
                  padding-top: 20px;
                }
                @media print {
                  body {
                    padding: 20px;
                  }
                  .day-section {
                    page-break-inside: avoid;
                  }
                }
              </style>
            </head>
            <body>
              <div class="header">
                <h1>${itinerary.title}</h1>
              </div>
              
              <div class="info-section">
                <div class="info-row">
                  <span class="info-label">开始日期：</span>
                  <span>${itinerary.start_date}</span>
                </div>
                <div class="info-row">
                  <span class="info-label">结束日期：</span>
                  <span>${itinerary.end_date}</span>
                </div>
                <div class="info-row">
                  <span class="info-label">总预算：</span>
                  <span>¥${itinerary.total_budget}</span>
                </div>
                <div class="info-row">
                  <span class="info-label">天数：</span>
                  <span>${daysCount} 天</span>
                </div>
              </div>
          `
          
          // 添加每日计划
          if (days.length > 0) {
            days.forEach((day) => {
              htmlContent += `
                <div class="day-section">
                  <div class="day-header">第${day.day_number}天 - ${day.date}</div>
                  <div class="day-content">
              `
              
              if (day.activities && day.activities.length > 0) {
                day.activities.forEach((activity) => {
                  htmlContent += `
                    <div class="activity-item">
                      <div class="activity-title">${activity.attraction_name || activity.attraction?.name || '未知景点'}</div>
                      <div class="activity-detail">⏰ 时间：${activity.start_time} - ${activity.end_time}</div>
                      <div class="activity-detail">🚗 交通方式：${getTransportModeName(activity.transport_mode)}</div>
                      ${activity.notes ? `<div class="activity-detail">📝 备注：${activity.notes}</div>` : ''}
                    </div>
                  `
                })
              } else {
                htmlContent += '<div class="activity-detail">暂无活动安排</div>'
              }
              
              htmlContent += `
                  </div>
                </div>
              `
            })
          } else {
            htmlContent += '<div class="day-section"><div class="day-content">暂无每日计划</div></div>'
          }
          
          // 添加提醒信息
          if (reminders.value && reminders.value.length > 0) {
            htmlContent += `
              <div class="reminders-section">
                <h2 style="color: #C8102E; margin-bottom: 20px;">行程提醒</h2>
            `
            
            reminders.value.forEach((reminder) => {
              htmlContent += `
                <div class="reminder-item">
                  <div style="font-weight: bold; margin-bottom: 8px;">
                    ${getReminderTypeName(reminder.reminder_type)} - ${formatReminderTime(reminder.reminder_time)}
                  </div>
                  <div class="activity-detail">消息：${reminder.message}</div>
                  <div class="activity-detail">状态：${getStatusName(reminder.status)}</div>
                  <div class="activity-detail">启用：${reminder.is_enabled ? '是' : '否'}</div>
                </div>
              `
            })
            
            htmlContent += '</div>'
          }
          
          htmlContent += `
              <div class="footer">
                <p>导出时间：${new Date().toLocaleString('zh-CN')}</p>
                <p>南昌旅游规划系统</p>
              </div>
            </body>
            </html>
          `
          
          // 打开新窗口并打印
          const printWindow = window.open('', '_blank')
          printWindow.document.write(htmlContent)
          printWindow.document.close()
          
          // 等待内容加载后打印
          printWindow.onload = () => {
            setTimeout(() => {
              printWindow.print()
              ElMessage.success('PDF导出已启动，请使用浏览器的打印功能保存为PDF')
            }, 250)
          }
        } catch (error) {
          import('../utils/logger').then(({ logger }) => {
            logger.error('导出PDF失败:', error)
          })
          ElMessage.error('导出PDF失败，请重试')
        }
      }
    }

    const reminderCheckInterval = ref(null)

    onMounted(async () => {
      fetchItineraries()
      
      // 请求通知权限
      await requestNotificationPermission()
      
      // 立即检查一次
      await checkUpcomingReminders()
      
      // 每5分钟检查一次即将到来的提醒
      reminderCheckInterval.value = setInterval(checkUpcomingReminders, 5 * 60 * 1000)
    })

    onUnmounted(() => {
      // 清理定时器
      if (reminderCheckInterval.value) {
        clearInterval(reminderCheckInterval.value)
        reminderCheckInterval.value = null
      }
    })

    return {
      loading,
      creating,
      updating,
      itineraries,
      showCreateDialog,
      showEditDialog,
      showDetailDialog,
      showReminderDialog,
      showActivityDialog,
      currentItinerary,
      formRef,
      editFormRef,
      reminderFormRef,
      activityFormRef,
      form,
      reminderForm,
      activityForm,
      activityRules,
      reminderRules,
      reminders,
      creatingReminder,
      togglingReminder,
      deletingReminder,
      creatingActivity,
      editingActivityId,
      deletingActivityId,
      attractions,
      loadingAttractions,
      rules,
      createItinerary,
      editItinerary,
      updateItinerary,
      viewItinerary,
      deleteItinerary,
      createReminder,
      toggleReminder,
      deleteReminder,
      showAddActivityDialog,
      editActivity,
      saveActivity,
      deleteActivity,
      resetActivityForm,
      getDaysCount,
      getTransportModeName,
      getReminderTypeName,
      getReminderTypeTag,
      getStatusName,
      getStatusTag,
      formatReminderTime,
      exportItinerary,
      Download,
      Document,
      Files,
      DocumentCopy,
      ArrowDown,
      isMobile
    }
  }
}
</script>

<style scoped>
.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  line-height: 1.5;
}
.itineraries {
  max-width: 1200px;
  margin: 0 auto;
  padding: clamp(10px, 2vw, 20px);
  /* 南昌旅游特色：天空蓝渐变背景 */
  background: linear-gradient(135deg, #E3F2FD 0%, #BBDEFB 50%, #90CAF9 100%);
  min-height: 100vh;
  animation: fadeIn 0.5s ease-in;
}

.itineraries :deep(.el-card) {
  border-radius: 12px;
  border: 1px solid rgba(200, 16, 46, 0.1);
  background: linear-gradient(135deg, rgba(255,255,255,0.95) 0%, rgba(227,242,253,0.8) 100%);
  backdrop-filter: blur(10px);
  box-shadow: 0 2px 12px rgba(200, 16, 46, 0.08);
  transition: all 0.3s ease;
}

.itineraries :deep(.el-card:hover) {
  box-shadow: 0 8px 24px rgba(200, 16, 46, 0.16);
  transform: translateY(-2px);
  border-color: rgba(212, 175, 55, 0.3);
}

.itineraries :deep(.el-card__header) {
  background: linear-gradient(135deg, rgba(200, 16, 46, 0.05) 0%, rgba(212, 175, 55, 0.05) 100%);
  border-bottom: 1px solid rgba(200, 16, 46, 0.1);
  border-radius: 12px 12px 0 0;
}

.itineraries :deep(.el-timeline-item__node) {
  background-color: #C8102E;
  border-color: #D4AF37;
}

.itineraries :deep(.el-timeline-item__tail) {
  border-left-color: rgba(200, 16, 46, 0.2);
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 移动端优化 */
@media (max-width: 768px) {
  .itineraries {
    padding: 10px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .activity-item {
    padding: 10px;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.activity-item {
  margin-bottom: 15px;
  padding: 15px;
  border-radius: 8px;
  border: 1px solid rgba(200, 16, 46, 0.1);
  background: linear-gradient(135deg, rgba(255,255,255,0.9) 0%, rgba(227,242,253,0.6) 100%);
  transition: all 0.3s ease;
}

.activity-item:hover {
  box-shadow: 0 4px 12px rgba(200, 16, 46, 0.12);
  transform: translateX(4px);
  border-color: rgba(212, 175, 55, 0.3);
}

.activity-item:last-child {
  margin-bottom: 0;
}

.activity-item h4 {
  margin: 0 0 10px 0;
  color: #C8102E;
  font-weight: 600;
  font-size: 16px;
}

.activity-item p {
  margin: 5px 0;
  color: #606266;
  font-size: 14px;
}

.activity-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.activity-actions {
  display: flex;
  gap: 8px;
}

.reminders-section {
  margin-top: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.section-header h3 {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

.reminders-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.reminder-card {
  transition: all 0.3s;
}

.reminder-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.reminder-content {
  flex: 1;
}

.reminder-info {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 8px;
}

.reminder-time {
  color: #606266;
  font-size: 14px;
}

.reminder-message {
  margin: 8px 0 0 0;
  color: #303133;
  font-size: 14px;
  line-height: 1.6;
}

.reminder-actions {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #ebeef5;
}
</style>

